package com.example.springboot.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.springboot.common.Constants;
import com.example.springboot.common.Result;
import com.example.springboot.entity.Dict;
import com.example.springboot.mapper.DictMapper;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

import com.example.springboot.service.IMenuService;
import com.example.springboot.entity.Menu;

import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author wgc
 * @since 2023-05-14
 */
@RestController
@RequestMapping("/menu")
public class MenuController {

    @Resource
    private IMenuService menuService;

    @Resource
    private DictMapper dictMapper;

    //新增和修改
    @PostMapping
    public Result save(@RequestBody Menu menu) {  //@RequestBody接收前端数据
        //新增或者更新
        menuService.saveOrUpdate(menu);
        return Result.success();
    }

    //查询所有数据
    @GetMapping()
    public Result findAll(@RequestParam(defaultValue = "") String name) {
        //  查出系统所有的菜单 与生成子菜单
        return Result.success(menuService.findMenus(name));
    }

    //删除
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        menuService.removeById(id);
        return Result.success();
    }

    //批量删除
    @PostMapping("/del/batch")
    public Result deleteBatch(@RequestBody List<Integer> ids) {
        menuService.removeByIds(ids);
        return Result.success();
    }

    // 重新所有菜单id
    /**
     .stream() 将菜单列表转换为一个流（Stream），以便对每个菜单进行进一步的处理。
     .map(Menu::getId) 对每个菜单对象应用 getId() 方法，将菜单对象转换为对应的菜单的ID。
     */
    @GetMapping("/ids")
    public Result findAll(){
        // 查出数据库表里所有的菜单id,跟当前选择的菜单id进行比较
        return Result.success(menuService.list().stream().map(Menu::getId));
    }

    @GetMapping("/{id}")
    public Result findOne(@PathVariable Integer id) {
        return Result.success(menuService.getById(id));
    }

    @GetMapping("/page")
    public Result findPage(
            @RequestParam String name,
            @RequestParam Integer pageNum,
            @RequestParam Integer pageSize) {

        QueryWrapper<Menu> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("id");
        queryWrapper.like("name", name);
        return Result.success(menuService.page(new Page<>(pageNum, pageSize), queryWrapper));
    }

    @GetMapping("/icons")
    public Result getIcons() {
        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("type", Constants.DICT_ICON);
        return Result.success(dictMapper.selectList(queryWrapper));
    }
}



